#include <cmd/common.h>
#include "mqtt.h"

std::shared_ptr<mqttplus> mqttplus::_inst;

mqttplus::mqttplus(){
    std::string mqtt_host = settings.get<std::string>("mqtt.host", "192.168.5.178");
    settings.put("mqtt.host",mqtt_host);
    int mqtt_port = settings.get<int>("mqtt.port", 1883);
    settings.put("mqtt.port",mqtt_port);
    c = MQTT_NS::make_sync_client(io, mqtt_host, mqtt_port);
    using packet_id_t = typename std::remove_reference_t<decltype(*c)>::packet_id_t;
    std::thread([&]{
        try{
        c->set_client_id("capture");
        c->set_clean_session(true);
        c->set_connack_handler([&](bool sp, MQTT_NS::connect_return_code connack_return_code){
            if (connack_return_code == MQTT_NS::connect_return_code::accepted) {
                c->subscribe("topic_vibration_feature_data", MQTT_NS::qos::exactly_once);
                c->subscribe("topic_record_feature_data", MQTT_NS::qos::exactly_once);
            }
            return true;
        });
        c->set_close_handler([](){BOOST_LOG_TRIVIAL(info) << "capture mqtt closed.";});
        c->set_error_handler([](MQTT_NS::error_code ec){BOOST_LOG_TRIVIAL(info) << "capture mqtt error: " << ec.message();});
        c->connect();
        io.run();
        }catch(...){
            BOOST_LOG_TRIVIAL(error)<<"mqtt connect fail.";
        }
    }).detach();
    
}

bool mqttplus::publish(std::string topic,std::string msg){
    try{
        if(c.get()){
            std::lock_guard<std::mutex> lock(mtx);
            c->publish(topic, msg,MQTT_NS::qos::exactly_once);
        }
    }catch(...){
        BOOST_LOG_TRIVIAL(warning)<<"mqtt publish fail.";
    }
    return true;
}